<?php
namespace Controllers;

use Models\User;

class UserController extends CommonController {



    public function login() {
        return $this->render('user/login');
    }

    public function doLogin() {
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        if (empty($username)) return $this->jsonResponse(0, '用户名必须填写');
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        if (empty($password)) return $this->jsonResponse(0, '密码必须填写');
        $re_password = isset($_POST['re_password']) ? $_POST['re_password'] : '';

        $userModel = new User();
        $userData = $userModel->getUserByUsername($username);
        if (empty($userData)) return $this->jsonResponse(0, '用户名不存在');
        if (md5($password) != $userData['password']) return $this->jsonResponse(0, '密码不正确');

        $_SESSION['username'] = $username;
        return $this->jsonResponse(1, '登录成功', $userData);

    }

    public function register() {
        return $this->render('user/register');
    }
    public function doRegister() {
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        if (empty($username)) return $this->jsonResponse(0, '用户名必须填写');
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        if (empty($password)) return $this->jsonResponse(0, '密码必须填写');
        $re_password = isset($_POST['re_password']) ? $_POST['re_password'] : '';
        if (empty($re_password)) return $this->jsonResponse(0, '确认密码必须填写');
        if ($password != $re_password) return $this->jsonResponse(0, '两次密码不一致');
        // 是否注册 模拟使用数据库
        $userModel = new User();
        if ($userModel->getUserByUsername($username))
            return $this->jsonResponse(0, '用户名已存在');
        $data = [
            'username' => $username,
            'password' => md5($password)
        ];
        if(!$userModel->create($data)) {
            return $this->jsonResponse(0, '注册失败');
        }
        return $this->jsonResponse(1, '注册成功');
    }
}